package cn.mandy.sysadmin.service.impl;

import cn.mandy.sysadmin.common.util.MandyTree;
import cn.mandy.sysadmin.constant.MandyConstant;
import cn.mandy.sysadmin.dao.MonitorJobDao;
import cn.mandy.sysadmin.dao.MonitorTaskDao;
import cn.mandy.sysadmin.dto.MonitorLogFileParam;
import cn.mandy.sysadmin.dto.MyId;
import cn.mandy.sysadmin.dto.TaskRefreshParam;
import cn.mandy.sysadmin.mapper.*;
import cn.mandy.sysadmin.model.*;
import cn.mandy.sysadmin.service.MonitorService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Description :
 *
 * @author <a href= "mailto:342987890@qq.com">Winter</a>
 * create date: 2020/4/13 0013
 * project: sysadmin
 * @since
 */
@Service
@Transactional
public class MonitorServiceImpl implements MonitorService {
    @Autowired
    private MonitorGlobalMapper monitorGlobalMapper;

    @Autowired
    private MonitorHostMapper monitorHostMapper;

    @Autowired
    private MonitorJobMapper monitorJobMapper;

    @Autowired
    private MonitorJobDao monitorJobDao;

    @Autowired
    private MonitorTaskMapper monitorTaskMapper;

    @Autowired
    private MonitorTaskDao monitorTaskDao;

    @Autowired
    private MonitorPlanMapper monitorPlanMapper;

    @Autowired
    private MonitorDependenceMapper monitorDependenceMapper;


    @Override
    public List<MonitorGlobal> globalList() {
        return monitorGlobalMapper.selectByExample(null);
    }

    @Override
    public int globalUpdate(MonitorGlobal newParam) {
        MonitorGlobal newGlobal = new MonitorGlobal();
        newGlobal.setId(newParam.getId());
        newGlobal.setParamValue(newParam.getParamValue());
        newGlobal.setRemark(newParam.getRemark());
        int ret = monitorGlobalMapper.updateByPrimaryKeySelective(newGlobal);
        if (ret == 1) {
            return 0;
        }

        return 1;
    }

    @Override
    public List<MonitorHost> monitorHostList() {
        List<MonitorHost> monitorHosts = monitorHostMapper.selectByExample(null);
        return monitorHosts;
    }

    @Override
    public int monitorHostUpdate(MonitorHost newHost) {
        newHost.setCreateTime(null);
        int ret = monitorHostMapper.updateByPrimaryKeySelective(newHost);
        if (ret == 1) {
            return 0;
        }
        return 1;
    }

    @Override
    public MonitorHost cfgHostCopy(MonitorHost oldHost) {
        //新复制过来的主机, 要修改信息后才可用.
        oldHost.setCreateTime(null);
        oldHost.setId(null);
        oldHost.setIzEnabled("0");
        int ret = monitorHostMapper.insert(oldHost);
        if (ret == 1) {
            return oldHost;
        }

        return null;
    }


    @Override
    public void monitorJobResort(List<MyId> newOrdinal) {
        Integer i = 1;
        for (MyId jobId: newOrdinal) {
            MonitorJob job = new MonitorJob();
            job.setId(jobId.getId());
            job.setOrdinalPosition(i++);
            monitorJobMapper.updateByPrimaryKeySelective(job);
        }
    }


    @Override
    public int jobDelete(List<MyId> param) {
        //删除操作, 是逻辑删除, 把iz_deleted 置为 "1"
        //TODO 删除操作一定是在编辑状态下进行的。
        //     进入编辑状态一定是要在下线状态进行。
        //     作业下线操作, 会删除所有未执行的任务。
        //     作业组在运行状态时下线，会提示是否需要停止作业。

        MonitorJob cfgJob = new MonitorJob();
        for (MyId jobId: param) {
            if (jobId.getId() != null) {
                cfgJob.setId(jobId.getId());
                cfgJob.setIzDeleted("1");
                monitorJobMapper.updateByPrimaryKeySelective(cfgJob);
            }
        }

        return 0;
    }


    @Override
    public MonitorJob monitorJobUpdate(MonitorJob paramJobGroup) {
        System.out.println("cfgJobUpdate");
        System.out.println(JSON.toJSON(paramJobGroup));
        if (paramJobGroup.getChildren() != null && paramJobGroup.getChildren().size() > 0){
            Integer i = 1;
            Integer i2 = 0;
            String priorSerialProcessing = MandyConstant.SerialProcessing.SERIAL;

            for (MonitorJob paramJob: paramJobGroup.getChildren()) {
                paramJob.setParentId(paramJobGroup.getId());

                paramJob.setOrdinalPosition(i++);
                if (paramJob.getSerialProcessing().equals(MandyConstant.SerialProcessing.SERIAL)){
                    paramJob.setOrdinalPosition2(++i2);
                    priorSerialProcessing = MandyConstant.SerialProcessing.SERIAL;
                }else if (paramJob.getSerialProcessing().equals(priorSerialProcessing)){
                    paramJob.setOrdinalPosition2(i2);
                }else{
                    paramJob.setOrdinalPosition2(++i2);
                    priorSerialProcessing = MandyConstant.SerialProcessing.PARALLEL;
                }

                if (paramJob.getId() == null){
                    insertOneCfgJob(paramJob);
                }else{
                    //更新
                    paramJob.setConfigTime(null);
                    paramJob.setIzDeleted("0");
                    monitorJobMapper.updateByPrimaryKeySelective(paramJob);
                }
            }
        }

        MonitorJob newJobGroup = new MonitorJob();
        newJobGroup.setId(paramJobGroup.getId());
        newJobGroup.setJobName(paramJobGroup.getJobName());
        newJobGroup.setJobType(paramJobGroup.getJobType());
        newJobGroup.setMaxParallel(paramJobGroup.getMaxParallel());
        newJobGroup.setMaxDuration(paramJobGroup.getMaxDuration());
        newJobGroup.setParentId(paramJobGroup.getParentId());
        //更新过的作业,要重新进行上线操作,触发执行计划数据的重新生成
        newJobGroup.setIzEnabled("0");
        int ret = monitorJobMapper.updateByPrimaryKeySelective(newJobGroup);
        if (ret == 1) {
            List<MonitorJob> cfgJobs = monitorJobDao.listCfgJobGroup(paramJobGroup.getId());
            return MandyTree.listToTree(cfgJobs).get(0);
        }

        return null;
    }


    private MonitorJob insertOneCfgJob(MonitorJob cfgJob){
        //新复制过来的作业, 只是复制部份信息, 要修改信息后才可用.
        cfgJob.setConfigTime(null);
        cfgJob.setId(null);
        cfgJob.setIzDeleted("0");
        //新的作业需要上线操作才能生效
        cfgJob.setIzEnabled("0");
        cfgJob.setHasDependence("0");

        int ret = monitorJobMapper.insert(cfgJob);
        if (ret == 1) {
            return cfgJob;
        }
        return null;
    }

    @Override
    public MonitorJob monitorJobGroupCopy(MonitorJob cfgJob) {

        List<MonitorJob> newChildren = new ArrayList<>();
        cfgJob.setOrdinalPosition(cfgJob.getOrdinalPosition()+1);
        if (MandyConstant.JobType.DAEMON.equals(cfgJob.getJobType())){
            cfgJob.setOrdinalPosition2(1);
        }
        MonitorJob newJob = insertOneCfgJob(cfgJob);
        MonitorJob updateParentId = new MonitorJob();
        updateParentId.setId(newJob.getId());
        updateParentId.setParentId(newJob.getId());
        monitorJobMapper.updateByPrimaryKeySelective(updateParentId);
        if (newJob != null) {
            if (cfgJob.getChildren() != null) {
                for (MonitorJob child : cfgJob.getChildren()) {
                    child.setParentId(newJob.getId());
                    child.setJobName(child.getJobName()+"_copy");
                    if (MandyConstant.JobType.DAEMON.equals(child.getJobType())){
                        child.setOrdinalPosition2(1);
                    }
                    MonitorJob newChild = insertOneCfgJob(child);
                    if (newChild != null) {
                        newChildren.add(newChild);
                    }
                }
                newJob.setChildren(newChildren);
            }
        }

        return newJob;
    }

    private void jobEnableDisable(List<MyId> myIds, String value){
        List<Long> ids = new ArrayList<>();
        for (MyId myId: myIds) {
            ids.add(myId.getId());
        }
        MonitorJobExample cfgJobExample = new MonitorJobExample();
        cfgJobExample.createCriteria().andIdIn(ids);
        MonitorJob record = new MonitorJob();
        record.setIzEnabled(value);
        monitorJobMapper.updateByExampleSelective(record, cfgJobExample);
    }

    /**
     * 作业组上线, 其下的作业的执行计划要单独地逐一启用。
     * @param param
     */
    @Override
    public void jobEnable(List<MyId> param) {
        jobEnableDisable(param, MandyConstant.HostIsEnabled.ENABLED);
    }

    /**
     * 作业下线，作业下的计划也都要撤消.
     * @param param
     */
    @Override
    public void jobDisable(List<MyId> param) {
        planDisableByJobId(param);
        jobEnableDisable(param, MandyConstant.HostIsEnabled.DISABLED);
    }

    @Override
    public List<MonitorJob> monitorJobList() {
        return monitorJobDao.listAllCfgJob();
    }

    private List<MonitorTask> listTaskByMyIds(List<MyId> myIds){
        if (myIds == null || myIds.isEmpty()){
            return null;
        }
        List<Long> parentIds = new ArrayList<>();
        for (MyId aId : myIds) {
            parentIds.add(aId.getId());
        }
        MonitorTaskExample taskExample = new MonitorTaskExample();
        taskExample.createCriteria().andParentIdIn(parentIds);
        taskExample.setOrderByClause(" schedule_time, id ");
        List<MonitorTask> groupTaskProcesses =  monitorTaskMapper.selectByExample(taskExample);
        return groupTaskProcesses;
    }


    private List<MonitorTask> listTaskNearByScheduleTime(Long jobId, Date schedulerTime, int recordCount, Long taskId) {
        int afterCount = 5;
        int beforeCount = recordCount - afterCount;
        if (beforeCount < 0) {
            beforeCount = 2;
        }

        MonitorTaskExample taskExample = new MonitorTaskExample();
        taskExample.createCriteria()
                 .andScheduleTimeLessThanOrEqualTo(schedulerTime)
                 .andJobIdEqualTo(jobId);
        taskExample.setOrderByClause("schedule_time desc limit " + beforeCount);
        List<MonitorTask> beforeTaskProcess = monitorTaskMapper.selectByExample(taskExample);


        List<MonitorTask> afterTaskProcess = listTaskAfter(jobId, schedulerTime, afterCount);

        List<MonitorTask> retList = reverseList(beforeTaskProcess);
        retList.addAll(afterTaskProcess);

        return retList;
    }

    private List<MonitorTask> reverseList(List<MonitorTask> taskProcesses){
        List<MonitorTask> retList = new LinkedList<>();
        for (MonitorTask task: taskProcesses) {
            retList.add(0, task);
        }
        return retList;
    }

    @Override
    public List<MonitorTask> listTaskBefore(Long jobId, Date scheduleTime, int recordCount) {
        MonitorTaskExample taskExample = new MonitorTaskExample();
        taskExample.createCriteria()
                .andScheduleTimeLessThan(scheduleTime)
                .andJobIdEqualTo(jobId);
        taskExample.setOrderByClause("schedule_time desc limit " + recordCount);
        List<MonitorTask> beforeTaskProcess = monitorTaskMapper.selectByExample(taskExample);

        return reverseList(beforeTaskProcess);
    }

    @Override
    public List<MonitorTask> listTaskAfter(Long jobId, Date scheduleTime, int recordCount) {
        if (jobId == null || scheduleTime == null){
            return null;
        }
        MonitorTaskExample taskExample = new MonitorTaskExample();
        taskExample.createCriteria()
                .andScheduleTimeGreaterThan(scheduleTime)
                .andJobIdEqualTo(jobId);
        taskExample.setOrderByClause("schedule_time limit " + recordCount);
        return monitorTaskMapper.selectByExample(taskExample);
    }

    private List<MonitorTask> listTaskByMyIds(List<MyId> idsBefore, Long taskParentId, List<MyId> idsAfter){
        MyId myId = new MyId();
        myId.setId(taskParentId);
        idsBefore.add(myId);
        idsBefore.addAll(idsAfter);

        List<MonitorTask> ret = listTaskByMyIds(idsBefore);
        return ret;
    }

    @Override
    public  MonitorTask getCurrentTask(Long jobId){
        MonitorJob jobStatus = monitorJobMapper.selectByPrimaryKey(jobId);
        if (jobStatus == null || jobStatus.getCurrentTaskId() == null) {
            return null;
        }
        return monitorTaskMapper.selectByPrimaryKey(jobStatus.getCurrentTaskId());
    }


    @Override
    public List<MonitorTask> listChildrenCurrentTask(Long jobId, int recordCount) {
        MonitorTask taskProcess = getCurrentTask(jobId);

        if (null == taskProcess){
            taskProcess = new MonitorTask();
            Date now = monitorTaskDao.getCurrentDate();
            taskProcess.setScheduleTime(now);
        }

        int afterCount = 5;
        int beforeCount = recordCount - afterCount;
        if (beforeCount < 0) {
            beforeCount = 2;
        }

        List<MyId> idsBefore = monitorTaskDao.listAllChildrenTaskBefore(jobId, taskProcess.getScheduleTime(), beforeCount);
        List<MyId> idsAfter = monitorTaskDao.listAllChildrenTaskAfter(jobId, taskProcess.getScheduleTime(), beforeCount);

        List<MonitorTask> ret = listTaskByMyIds(idsBefore, taskProcess.getParentId(), idsAfter);
        resetParentIdWithOldId(ret);
        return ret;
    }

    @Override
    public List<MonitorTask> listAllChildrenTaskBefore(Long jobId, Date schedulerTime, int recordCount) {
        List<MyId> idsBefore = monitorTaskDao.listAllChildrenTaskBefore(jobId, schedulerTime, recordCount);
        List<MonitorTask> ret = listTaskByMyIds(idsBefore);
        resetParentIdWithOldId(ret);
        return ret;
    }

    @Override
    public List<MonitorTask> listAllChildrenTaskAfter(Long jobId, Date schedulerTime, int recordCount) {
        List<MyId> idsAfter = monitorTaskDao.listAllChildrenTaskAfter(jobId, schedulerTime, recordCount);
        List<MonitorTask> ret = listTaskByMyIds(idsAfter);
        resetParentIdWithOldId(ret);
        return ret;
    }


    @Override
    public List<MonitorTask> taskRefresh(TaskRefreshParam taskRefreshParam) {
        MonitorTask task = this.getCurrentTask(taskRefreshParam.getJobId());
        if (null == task){
            return null;
        }
        List<MonitorTask> tasks;
        if (MandyConstant.JobType.DAEMON_GROUP.equals(task.getJobType())
                || MandyConstant.JobType.NORMAL_GROUP.equals(task.getJobType())) {
            tasks = monitorTaskDao.refreshTaskGroupList(taskRefreshParam.getJobId(), task.getId(), task.getScheduleTime(), taskRefreshParam.getEndTime());
            resetParentIdWithOldId(tasks);
            return MandyTree.listToTree(tasks);
        }else{
            tasks = monitorTaskDao.refreshTaskList(taskRefreshParam.getJobId(), task.getId(), task.getScheduleTime(), taskRefreshParam.getEndTime());
            return tasks;
        }

    }

    @Override
    public MonitorPlan planCreate(MonitorPlan monitorPlan){
        monitorPlanMapper.insert(monitorPlan);
        return monitorPlan;
    }

    private void planEnableDisableById(List<MyId> myIds, String value){
        List<Long> ids = new ArrayList<>();
        for (MyId myId: myIds) {
            ids.add(myId.getId());
        }
        MonitorPlanExample monitorPlanExample = new MonitorPlanExample();
        monitorPlanExample.createCriteria().andIdIn(ids);
        MonitorPlan record = new MonitorPlan();
        record.setIzEnabled(value);
        monitorPlanMapper.updateByExampleSelective(record, monitorPlanExample);
    }

    private void planDisableByJobId(List<MyId> myIds){
        List<Long> ids = new ArrayList<>();
        for (MyId myId: myIds) {
            ids.add(myId.getId());
        }
        MonitorPlanExample monitorPlanExample = new MonitorPlanExample();
        monitorPlanExample.createCriteria().andJobIdIn(ids);
        MonitorPlan record = new MonitorPlan();
        record.setIzEnabled(MandyConstant.HostIsEnabled.DISABLED);
        monitorPlanMapper.updateByExampleSelective(record, monitorPlanExample);
    }

    @Override
    public int planEnable(List<MyId> myIds) {
        planEnableDisableById(myIds, MandyConstant.HostIsEnabled.ENABLED);
        return 0;
    }

    @Override
    public int planDisable(List<MyId> myIds) {
        planEnableDisableById(myIds, MandyConstant.HostIsEnabled.DISABLED);
        //delete from task_process where crontab_id = NEW.id;
        //monitorTaskMapper
        return 0;
    }

    @Override
    public int planDelete(List<MyId> ids) {
        for (MyId myId: ids) {
            monitorPlanMapper.deleteByPrimaryKey(myId.getId());
        }
        return 0;
    }

    @Override
    public List<MonitorDependence> dependenceUpdate(List<MonitorDependence> jobDependencies) {
        if (jobDependencies == null || jobDependencies.size() == 0){
            return null;
        }

        for (MonitorDependence dependence: jobDependencies ) {
            if (dependence.getId() == null){
                monitorDependenceMapper.insert(dependence);
            }else{
                monitorDependenceMapper.updateByPrimaryKey(dependence);
            }
        }

        MonitorJob cfgJob = new MonitorJob();
        cfgJob.setId(jobDependencies.get(0).getJobId());
        cfgJob.setHasDependence("1");
        monitorJobMapper.updateByPrimaryKeySelective(cfgJob);

        MonitorDependenceExample cfgJobDependenceExample = new MonitorDependenceExample();
        cfgJobDependenceExample.createCriteria().andJobIdEqualTo(jobDependencies.get(0).getJobId());
        cfgJobDependenceExample.setOrderByClause("id");

        return monitorDependenceMapper.selectByExample(cfgJobDependenceExample);
    }

    @Override
    public int dependenceDelete(List<MyId> ids) {
        if (ids == null || ids.size() == 0){
            return 0;
        }

        MonitorDependence cfgJobDependence = monitorDependenceMapper.selectByPrimaryKey(ids.get(0).getId());
        Long jobId = cfgJobDependence.getJobId();

        for (MyId myId: ids) {
            monitorDependenceMapper.deleteByPrimaryKey(myId.getId());
        }

        MonitorDependenceExample dependenceExample = new MonitorDependenceExample();
        dependenceExample.createCriteria().andJobIdEqualTo(jobId);
        dependenceExample.setOrderByClause("id");
        Long count =monitorDependenceMapper.countByExample(dependenceExample);
        if (count == 0){
            MonitorJob monitorJob = new MonitorJob();
            monitorJob.setId(jobId);
            monitorJob.setHasDependence("0");
            monitorJobMapper.updateByPrimaryKeySelective(monitorJob);
        }
        return 0;
    }

    /**
     * 0 指前面补充零
     * formatLength 字符总长度为 formatLength
     * inputNumber 格式化数字
     * d 代表为正数。
     */
    private String zfill(int formatLength,int formatNumber){
        String newString = String.format("%0"+formatLength+"d", formatNumber);
        return newString;
    }

    @Override
    public String getTaskLogfile(MonitorLogFileParam monitorLogFileParam) throws IOException {
        MonitorHostExample hostExample = new MonitorHostExample();
        hostExample.createCriteria().andNameEqualTo(monitorLogFileParam.getHostName());

        List<MonitorHost> hosts = monitorHostMapper.selectByExample(hostExample);
        if (hosts == null || hosts.isEmpty()){
            return null;
        }
        // 端口号写死 6666
        String hostIp = hosts.get(0).getIpAddr();

        Socket client = new Socket(hostIp, 6666);
        OutputStream os = client.getOutputStream();
        byte[] request_bytes = JSON.toJSON(monitorLogFileParam).toString().getBytes();
        int request_bytes_size = request_bytes.length;
        String strSendLen = zfill(12, request_bytes_size);
        os.write(strSendLen.getBytes());
        os.write(request_bytes);

        InputStream is = client.getInputStream();
        byte[] response_bytes_size = new byte[13];
        is.read(response_bytes_size, 0, 12);
        String strRecvLen =  new String(response_bytes_size ,0, 12,"UTF-8");
        int responseSize = Integer.valueOf(strRecvLen);
        System.out.println("response_size = " + responseSize);
        if (responseSize > 2*1024*1024){
            //每次不超2M, 否则报错
            return null;
        }
        byte[] response_bytes = new byte[responseSize + 1];
        int startPos = 0;
        int recvLen = 0;
        int remainLen = responseSize;
        while (true){
            recvLen = is.read(response_bytes, startPos, remainLen);
            if (recvLen > 0){
                remainLen = remainLen - recvLen;
                startPos = startPos + recvLen;
            }else {
                break;
            }
        }
        client.close();
        if (remainLen == 0){
            String str = new String(response_bytes, 0, responseSize, "utf-8");
            return str;
        }
        return null;
    }


    @Override
    public int taskCancel(Long taskId, String oldStatus, String destStatus, String reason) {
        if (null == oldStatus || null == taskId || null == destStatus){
            return 1;
        }

        MonitorTask task = monitorTaskMapper.selectByPrimaryKey(taskId);
        if (null == task || ! task.getStatus().equals(oldStatus)){
            return 1;
        }
        MonitorTask newTask = new MonitorTask();
        newTask.setId(taskId);
        newTask.setStatus(destStatus);

        Date currentDate = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strNow = df.format(currentDate);
        String myRemark =  strNow + " => "+ reason;
        if (null == task.getRemark() || task.getRemark().isEmpty()){
            newTask.setRemark(myRemark);
        }else {
            newTask.setRemark(task.getRemark() + ";" + myRemark);
        }
        monitorTaskMapper.updateByPrimaryKeySelective(newTask);
        return 0;
    }

//    int createTaskNow(TaskProcess taskProcess);
//    int launchTaskNow(Long jobId);
    @Override
    public MonitorTask taskCreateNow(Long jobId) {
        MonitorTask task = new MonitorTask();
        task.setJobId(jobId);
        monitorTaskDao.createTaskNow(task);

        MonitorTask updateTask = new MonitorTask();
        updateTask.setId(task.getId());
        updateTask.setParentId(task.getId());
        updateTask.setOldId(task.getId());
        monitorTaskMapper.updateByPrimaryKeySelective(updateTask);
        return task;
    }

    @Override
    public MonitorTask selectTaskById(Long taskId) {
        return monitorTaskMapper.selectByPrimaryKey(taskId);
    }


    /**
     * 取消状态的任务, 区分开有没有到达执行时间，如果没有到达执行时间, 直接把状态回写为 未运行。
     * @param taskId
     * @return
     */
    @Override
    public MonitorTask taskRedoNow(Long taskId) {
        MonitorTask task = monitorTaskMapper.selectByPrimaryKey(taskId);
        if (MandyConstant.TaskStatus.CANCELED.equals(task.getStatus())){
            Date now = monitorTaskDao.getCurrentDate();
            if (now.before(task.getScheduleTime())){
                MonitorTask updateTask = new MonitorTask();
                updateTask.setId(taskId);
                updateTask.setStatus(MandyConstant.TaskStatus.INIT);
                monitorTaskMapper.updateByPrimaryKeySelective(updateTask);
                return updateTask;
            }
        }

        MonitorTask oldTask = new MonitorTask();
        oldTask.setId(taskId);
        oldTask.setHasRedo(MandyConstant.YesOrNo.YES);
        monitorTaskMapper.updateByPrimaryKeySelective(oldTask);

        MonitorTask taskProcess = new MonitorTask();
        taskProcess.setOldId(taskId);
        monitorTaskDao.redoTaskNow(taskProcess);
        monitorTaskDao.launchTaskRedoNow(taskProcess.getId());
        return taskProcess;
    }

    private void resetParentIdWithOldId(List<MonitorTask> taskProcesses){
        if (taskProcesses == null || taskProcesses.isEmpty()){
            return;
        }
        for (MonitorTask item: taskProcesses) {
            if (!item.getId().equals(item.getOldId())) {
                item.setParentId(item.getOldId());
            }
        }

    }

    @Override
    public List<MonitorTask> currentTaskListByJobGroupId(Long jobGroupId) {
        MonitorTask task = this.getCurrentTask(jobGroupId);
        if (null == task){
            return null;
        }
        MonitorTaskExample taskProcessExample = new MonitorTaskExample();
        taskProcessExample.createCriteria().andParentIdEqualTo(task.getParentId());
        List<MonitorTask> tasks = monitorTaskMapper.selectByExample(taskProcessExample);
        resetParentIdWithOldId(tasks);
        return tasks;
    }

    /**
     * -- 正在运行状态才停止 2-->w
     * if _status = '2'
     *     其下进程 1,2,8->9 ; 0,7->e;
     */
    @Override
    public int taskGroupStop(Long jobId, Long taskId, String status) {
        //检查当前状态与用户操作时的状态是否一致, 不一致的话返回失败
        if (taskId  == null || jobId == null || status == null){
            return 1;
        }
        MonitorTask taskProcess = this.getCurrentTask(jobId);
        if (! MandyConstant.TaskStatus.RUNNING.equals(taskProcess.getStatus())){
            return 1;
        }
        if (!taskId.equals(taskProcess.getId())){
            return 1;
        }
        if (!status.equals(taskProcess.getStatus())){
            return 1;
        }

        MonitorTask updateTask = new MonitorTask();
        // 任务组标注为正在停止, 由后台处理其它逻辑.
        updateTask.setStatus(MandyConstant.TaskStatus.READY_SHUTDOWN);
        updateTask.setShutdownTime(monitorTaskDao.getCurrentDate());
        updateTask.setId(taskId);
        monitorTaskMapper.updateByPrimaryKeySelective(updateTask);

        return 0;
    }

    @Override
    public List<MonitorTask> listCurrentTask(Long jobId, int recordCount) {
        MonitorTask taskProcess = getCurrentTask(jobId);
        return listTaskNearByScheduleTime(jobId, taskProcess.getScheduleTime(), recordCount, taskProcess.getParentId());
    }


}


